package main

import (
	"net"
	"strings"
)

type User struct {
	Name   string
	Addr   string
	C      chan string
	conn   net.Conn
	server *Server
}

func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name:   userAddr,
		Addr:   userAddr,
		C:      make(chan string),
		conn:   conn,
		server: server,
	}
	go user.ListenMessage()
	return user
}

func (user *User) Online() {
	server := user.server
	server.mapLock.Lock()
	server.OnlineMap[user.Name] = user
	server.mapLock.Unlock()

	server.BroadCast(user, "已上线")
}

func (user *User) Offline() {
	server := user.server
	server.mapLock.Lock()
	delete(server.OnlineMap, user.Name)
	server.mapLock.Unlock()

	server.BroadCast(user, "已下线")
}

func (user *User) sendMsg(msg string) {
	user.conn.Write([]byte(msg))
}

func (user *User) DoMessage(msg string) {
	server := user.server
	if msg == "who" {
		var onlineMsg string
		server.mapLock.Lock()
		for _, onlineUser := range server.OnlineMap {
			onlineMsg += "[" + onlineUser.Name + "]\n"
		}
		server.mapLock.Unlock()
		user.sendMsg(onlineMsg)
	} else if len(msg) > 6 && msg[:6] == "rename" {
		newName := msg[6:]
		_, ok := server.OnlineMap[newName]
		if ok {
			user.sendMsg("用户名已经存在\n")
		} else {
			server.mapLock.Lock()
			delete(server.OnlineMap, user.Name)
			server.OnlineMap[newName] = user
			server.mapLock.Unlock()
			user.Name = newName
			user.sendMsg("更新成功\n")
		}
	} else if len(msg) > 2 && msg[:2] == "to" {
		strArr := strings.Split(msg, "|")
		remoteName := strArr[0][2:]
		remoteUser, ok := server.OnlineMap[remoteName]
		if !ok {

		}
		remoteUser.sendMsg(strArr[1] + "\n")
	} else {
		server.BroadCast(user, msg)
	}
}

func (user *User) ListenMessage() {
	for {
		msg := <-user.C
		user.sendMsg(msg + "\n")
	}
}
